package com.pingan.haofang.searchcloud.common.redis;

import com.pingan.haofang.searchcloud.index.constants.IndexBuildConstants;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.Objects;

/**
 * @author baojimin
 * @date 2018/11/19
 * @since 1.0.0
 */
public class RedisQueueManager {

    static Logger LOG = LoggerFactory.getLogger(RedisQueueManager.class);

    private RedisTemplate redisTemplate;

    private RedisQueueManager() {
    }

    private static volatile RedisQueueManager manager;

    public static RedisQueueManager getInstanceOf(RedisTemplate redisTemplate) {
        if (manager == null) {
            synchronized (RedisQueueManager.class) {
                if (manager == null) {
                    manager = new RedisQueueManager();
                    manager.setRedisTemplate(redisTemplate);
                }
            }
        }
        return manager;
    }


    public Long pushMsg(String key, Object value) {
        if (Objects.isNull(key) || Objects.isNull(value)) {
            throw new IllegalArgumentException("key or value can not be null");
        }
        redisTemplate.opsForHash().put(IndexBuildConstants.INDEX_INC_KEY_HOLDER, key, String.valueOf(System.currentTimeMillis()));
        return redisTemplate.boundListOps(key).rightPush(value);
    }


    public <T> IncRedisQueue<T> buildMsgQueue(String key, RedisQueueListener<T> listener) {
        if (Objects.isNull(key) || Objects.isNull(listener)) {
            throw new IllegalArgumentException("key or listener can not be null");
        }
        return new IncRedisQueue<T>(key, redisTemplate, listener);
    }



    public RedisTemplate getRedisTemplate() {
        return redisTemplate;
    }

    public void setRedisTemplate(RedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
}
